﻿using System.Security.Cryptography.X509Certificates;
using Ipmce.RemoteVoting.Backend.VotingService.Contract;
using Ipmce.RemoteVoting.Common.Entities;
using Ipmce.RemoteVoting.Common.Tools;
using Ipmce.RemoteVoting.Common.Tools.Wcf;

namespace Ipmce.RemoteVoting.Frontend.VotingLibrary
{
	public class VoteImpl : IVote
	{
		private readonly IVoteEncryptor _dataEcryptor;

		public VoteImpl(IVoteEncryptor dataEcryptor)
		{
			_dataEcryptor = dataEcryptor;
		}

		public void Vote(Candidate candidate, string voter, string password, string confirmationId)
		{
			using (var client = new ServiceInterfaceProxy<IPassportVoting>("PassportVotingServiceEndPoint"))
			{
				if (client.ClientCredentials != null)
				{
					client.ClientCredentials.UserName.UserName = voter;
					client.ClientCredentials.UserName.Password = password;
				}
				client.GetInterface().Vote(_dataEcryptor.Encrypt(candidate), confirmationId);
			}
		}

		public void Vote(Candidate candidate, X509Certificate2 certificate, string confirmationId)
		{
			using (var client = new ServiceInterfaceProxy<ICertificateVoting>("CertificateVotingServiceEndPoint"))
			{
				if (client.ClientCredentials != null)
				{
					client.ClientCredentials.ClientCertificate.Certificate = certificate;
				}
				client.GetInterface().CertificateVote(_dataEcryptor.Encrypt(candidate), confirmationId);
			}
		}
	}
}